# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class PicwishPipeline:
    fp = None

    # 重写父类的方法：该方法旨在开始爬虫的时候被调用一次
    def open_spider(self, spider):
        print('开始爬虫······')
        self.fp = open('./msg.txt', 'w', encoding='utf-8')

    # 专门用来处理 item 类型对象
    # 该方法可以接收爬虫文件提交过来的 item 对象
    # 该方法每接收到一个 item 就会被调用一次
    def process_item(self, item, spider):
        img_msg = item['img_msg']
        img_url = item['img_url']

        # 持久化存储
        self.fp.write(img_msg + ' : ' + img_url + '\n')
        return item

    def close_spider(self, spider):
        print('结束爬虫！！！')
        self.fp.close()
